<template>
    <div class="avatar-upload">
        <el-upload class="avatar-uploader" action="dev_api/api/upload/avatar" :show-file-list="false"
            :before-upload="beforeUpload" :on-success="handleSuccess" :on-error="handleError">
            <img v-if="modelValue" :src="modelValue" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
                <Plus />
            </el-icon>
        </el-upload>

        <!-- 删除按钮 -->
        <div v-if="modelValue" class="avatar-actions">
            <el-button type="danger" link @click="handleDelete">
                删除头像
            </el-button>
        </div>
    </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import type { UploadProps } from 'element-plus'
import { delAvatar } from '@/api/file-manage'

const props = defineProps<{
    modelValue: string
}>()

const emit = defineEmits<{
    (e: 'update:modelValue', value: string): void
    (e: 'change', url: string): void
}>()



// 上传前验证
const beforeUpload: UploadProps['beforeUpload'] = (file) => {
    // 验证文件类型
    const isImage = ['image/jpeg', 'image/png', 'image/gif'].includes(file.type)
    if (!isImage) {
        ElMessage.error('只能上传图片文件!')
        return false
    }

    // 验证文件大小
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB!')
        return false
    }

    return true
}

// 上传成功
const handleSuccess: UploadProps['onSuccess'] = async (response) => {
    if (response.code === 200) {
        // 如果已有旧头像，先删除
        if (props.modelValue) {
            try {
                await delAvatar(props.modelValue)
            } catch (error) {
                console.error('旧头像删除失败:', error)
            }
        }
        
        const url = response.data.url
        emit('update:modelValue', url)
        emit('change', url)
        ElMessage.success('上传成功')
    } else {
        ElMessage.error(response.message || '上传失败')
    }
}

// 上传失败
const handleError: UploadProps['onError'] = () => {
    ElMessage.error('上传失败,请重试')
}

// 删除头像
const handleDelete = async () => {
    try {
        if (!props.modelValue) return
        await delAvatar(props.modelValue)
        emit('update:modelValue', '')
        emit('change', '')
        ElMessage.success('删除成功')
    } catch (error) {
        console.error('删除失败:', error)
        ElMessage.error('删除失败')
    }
}
</script>

<style scoped>
.avatar-upload {
    text-align: center;
}

.avatar-uploader {
    width: 100px;
    height: 100px;
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader:hover {
    border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    text-align: center;
    line-height: 100px;
}

.avatar {
    width: 100px;
    height: 100px;
    display: block;
    object-fit: cover;
}

.avatar-actions {
    margin-top: 8px;
}
</style>